extends Node2D


var blockCls = preload("res://Actors/Block.tscn")

var last_next_y = 200

var rng = RandomNumberGenerator.new()

var finished = false

# Called when the node enters the scene tree for the first time.
func _ready():
	$Block.connect("on_character_above", self, "OnCharacterAboveBlock")
	$Block2.connect("on_character_above", self, "OnCharacterAboveBlock")
	$Block3.connect("on_character_above", self, "OnCharacterAboveBlock")
	$Block4.connect("on_character_above", self, "OnCharacterAboveBlock")
	
	$Block.connect("on_block_visibility_exit", self, "OnBlockHide")
	$Block2.connect("on_block_visibility_exit", self, "OnBlockHide")
	$Block3.connect("on_block_visibility_exit", self, "OnBlockHide")
	$Block4.connect("on_block_visibility_exit", self, "OnBlockHide")
	
	$KillZone.connect("on_kill_character", self, "OnFinishGame")
	pass

func OnFinishGame():
	finished = true
	$Character.queue_free()

func OnBlockHide(blockName, posY):
	var bd = get_node(blockName)
	if bd != null:
		if !finished:
			if !bd.is_queued_for_deletion():
				var playerY = $Character.position.y
				# Y blow
				if posY > playerY:
					bd.queue_free()
		else:
			bd.queue_free()

func OnCharacterAboveBlock(posY):
	print("Block Check - 1")
	call_deferred("RandomGenBlock", last_next_y)
	MoveKillZone(posY)
	pass

func MoveKillZone(posY):
	var pos = $KillZone.position
	$KillZone.set("position", Vector2(pos.x, posY + 900))
	pass

# When

func RandomGenBlock(lastY):
	rng.randomize()
	var nextX = rng.randi_range(0, 460)
	var nextY = lastY
	
	rng.randomize()
	var height = rng.randi_range(60, 85)
	nextY -= height
	
	last_next_y = nextY
	
	# use 0
	var block = blockCls.instance(0)
	block.set("position", Vector2(nextX, nextY))
	block.connect("on_character_above", self, "OnCharacterAboveBlock")
	block.connect("on_block_visibility_exit", self, "OnBlockHide")
	add_child(block)
	
